let server = require('express')();
let mysql = require('mysql');
let port = 8080;


//解决跨域问题
server.all("*", function(req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200); //让options尝试请求快速结束
    else
        next();
})

// 规划链接
let sql = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '378507',
    database: 'login'
});
// 尝试链接
sql.connect();

server.get("/register", function(request, response) {
        let username = request.query.username;
        let password = request.query.password;
        console.log(username);
        console.log(password);
        //执行sql任务
        sql.query(`SELECT * FROM submit WHERE username="${username}"`, function(error, data) {
            if (error) {
                console.log(error)
                response.end("error")
                return;
            }
            if (data.length === 0) {
                sql.query(`INSERT INTO submit (username,password) VALUES ("${username}","${password}")`, function(error, data) {
                    if (error) {
                        console.log(error);
                        response.end("error");
                        return;
                    }
                    response.end("success");
                })
            } else {
                response.end("exist")
            }
        })
    })
    //if (data.length !== 0)
server.get("/login", function(request, response) {
    let username = request.query.username;
    let password = request.query.password;
    sql.query(`SELECT * FROM submit WHERE username="${username}"`, function(error, data) {
        if (error) {
            console.log(error);
            response.end("error");
            return;
        }
        if (data.length === 0) {
            response.end("error");
        } else {
            if (data[0].password == password) {
                response.end("success");
            } else {
                response.end("error");
            }
        }
    })
})

// 真正将上面的计划执行监听到本机的81端口上。
server.listen(port)

console.log(`服务器正常运行到本机的${port}端口上`);